#! /usr/bin env python3
# -*- coding:utf-8 -*-
"""
作者： kratos
时间： 2020年08月28日 21:39
用途：
"""
import json
from Util import Util
import requests

config_data = Util.all_config
token_url = config_data["API"]["token"]
tmp_send_url = config_data["API"]["tmpsend"] + "?access_token="
info_url = config_data["API"]["info"]


class wxAPI:
    def __init__(self):
        self.appid = config_data["wechat"]["appID"]
        self.secret = config_data["wechat"]["appsecret"]
        self.wechatID = config_data["wechat"]["wechatID"]
        self.tempID = config_data["wechat"]["tempID"]
        self.token = self.get_token()

    def get_token(self):
        params = {
            "grant_type": "client_credential",
            "appid": self.appid,
            "secret": self.secret
        }
        get_token_res = requests.get(url=token_url, params=params).json()
        if "errmsg" in get_token_res:
            Util.loger("获取token失败，错误码：%d，原因：%s" % (get_token_res["errcode"], get_token_res["errmsg"]))
            return False
        return get_token_res["access_token"]

    def send_msg_to_user(self, msg_dict: dict, page_name: str):
        real_tmp_send_url = tmp_send_url + self.token
        Util.loger(real_tmp_send_url, level="debug")
        data = {
            "touser": self.wechatID,
            "template_id": self.tempID,
            "url": info_url + "/logs/" + page_name,
            "data": msg_dict
        }

        headers = {'Content-Type': 'application/json'}
        Util.loger(str(data), level="debug")
        send_msg_res = requests.post(url=real_tmp_send_url, headers=headers, data=json.dumps(data))

        if send_msg_res.json()["errcode"]:
            Util.loger(send_msg_res.text, level="error")
        else:
            Util.loger("发送成功")
        return send_msg_res.json()


if __name__ == '__main__':
    api = wxAPI()
    msg_dict = {
        "title": {
            "value": "test",
            "color": "#173177"
        },
        "msg1": {
            "value": "test",
            "color": "#000000"
        }
    }
    api.send_msg_to_user(msg_dict)
